"""
调用控制器侧接口

"""

import json
import os
from datetime import datetime
from uuid import uuid4

import requests

from dotenv import load_dotenv

from apps.utils.tools import get_time_between
from components.mongo_connector import mongo_db
from components.mysql.connector import db

load_dotenv('env.ini', encoding='utf-8')


class Controller(object):
    def __init__(self, params=None):
        self.method_url = os.getenv('controller_url')

    def deal_resp(self, res):
        if res.get('error'):
            resp = {'error': res['error']['message']}
        else:
            resp = res.get('result')
        return resp

    def get_ports(self, **params):
        data = {
            'jsonrpc': '2.0',
            'id': str(uuid4()),
            "params": [params],
            "method": "getPorts"
        }
        resp = requests.post(self.method_url, json.dumps(data))
        return json.loads(resp.content)['result']


class KeyController(object):
    def __init__(self):
        self.base_url = os.getenv('controller_url')

    def deal_resp(self, resp):
        resp = resp.text
        if resp == 'The key was not found.':
            return []
        resp = json.loads('[' + resp + ']')
        return resp


class GetStatus(KeyController):
    def __init__(self):
        super().__init__()
        self.base_url = self.base_url + 'getstatus/'

    def get_info_with_date(self, key, date, splice_str='_'):
        value = str(key) + splice_str + str(date)
        url = self.base_url + value
        resp = requests.get(url)
        resp = self.deal_resp(resp)
        return resp

    # 获取流量
    def get_traffic(self, key, date):
        return self.get_info_with_date(key, date, splice_str='-')

    # 获取端口状态
    def physical_port_status(self, dev, haid, port):
        value = str(dev) + '-' + str(haid) + '-' + str(port)
        url = self.base_url + value
        resp = requests.get(url, verify=False)
        resp = self.deal_resp(resp)
        return resp

    # 获取路由表信息
    def ip_router(self, dev, haid):
        value = 'iproute_' + str(dev) + '-' + str(haid)
        url = self.base_url + value
        resp = requests.get(url)
        resp = self.deal_resp(resp)
        return resp

    # 光模块信息
    def transceiver(self, dev, haid, port):
        value = 'showtransceiver_' + str(dev) + '-' + str(haid) + '-' + str(port)
        url = self.base_url + value
        resp = requests.get(url, verify=False)
        resp = resp.text if resp.text != 'The key was not found.' else ''
        return resp


class GetStatusNew(object):
    def __init__(self):
        self.time_format = '%Y-%m-%d %H:%M:%S'

    def calculate_data(self, flows, new_start_date, new_end_date, type):
        """
        处理流量
        """
        # TODO 优化流量查询
        data = []
        time_dict = get_time_between(new_start_date, new_end_date, type)
        for flow in flows:
            flow['timestamp'] = str(flow['timestamp'])
            time_dict[str(flow['timestamp'])] = flow
        for k in time_dict:
            if not time_dict[k]:
                time_dict[k] = {
                    "output_bps": 0.0,
                    "input_bps": 0.0,
                }
            if 'output_bps' not in time_dict[k].keys():
                time_dict[k]['output_bps'] = int(time_dict[k]['output_bytes'] * 8 / 3600)
                time_dict[k]['input_bps'] = int(time_dict[k]['input_bytes'] * 8 / 3600)
            data.append({str(k): {"output_bps": time_dict[k]['output_bps'], "input_bps": time_dict[k]['input_bps']}})
        return data

    def get_traffic(self, conditions, start_date, end_date, type='mins'):
        """
        conditions 为 查询条件
        示例：
            all_flow = collection.find({"biz_id": controller_id, 'timestamp': })
        超过一个月读取biz_flow_hour,前端按照每小时展示
        一个月内的读取biz_flow_min,
        """
        if type == 'hours':
            collection_frequency = 'hour'
        else:
            collection_frequency = 'min'
        collection = mongo_db[f'biz_flow_{collection_frequency}']
        conditions['timestamp'] = {"$gte": start_date,
                                   "$lte": end_date}
        # 查询流量
        flows = collection.find(conditions, {'_id': 0})
        data = self.calculate_data(flows, start_date, end_date, type)
        return data

    def get_port_traffic(self, conditions, start_date, end_date, type='mins'):
        if type == 'hours':
            collection_frequency = 'hour'
        else:
            collection_frequency = 'min'
        collection = mongo_db[f'port_flow_{collection_frequency}']
        conditions['timestamp'] = {"$gte": start_date,
                                   "$lte": end_date}
        # 查询流量
        flows = collection.find(conditions, {'_id': 0})
        data = self.calculate_data(flows, start_date, end_date, type)
        return data

    def calculate_95(self, conditions, time_intervals=None):
        """
        {"key": 11, "95": 123}
        """
        data = []
        collection = mongo_db['95_flow']
        flows = collection.find(conditions, {'_id': 0})
        for flow in flows:
            info = [str(flow['timestamp']), flow['95']]
            data.append(info)
        return data

    def get_cfm(self, conditions, start_date, end_date):
        """
         a_device = link.a_device_port_ids.split('_')[0]
         查ControllerDevice.id
         a_device = Device.get_or_none(Device.id == a_device)
         去MongoDB表中拿取响应的延时数据,按照时间倒序,拿最新的
         a_link_delay = collection.find({"device_id": a_device.sign,
                                        'local_mep_id': link.a_mepid,
                                        'to_mep_id': link.z_mepid})
        """
        data = []
        time_format = '%Y-%m-%d %H:%M:%S'
        # new_start_date = datetime.strptime(start_date, time_format)
        # new_end_date = datetime.strptime(end_date, time_format)
        for_min = False
        if (start_date - end_date).days <= 30:
            for_min = True
        if for_min:
            time_dict = get_time_between(start_date, end_date, type='minute')
        else:
            time_dict = get_time_between(start_date, end_date, type='hours')

        collection = mongo_db['vll_delay']
        conditions['timestamp'] = {"$gte": start_date,
                                   "$lte": end_date},
        delays = collection.find(conditions)
        for delay in delays:
            if delay['timestamp'] not in time_dict.keys():
                time_dict[delay['timestamp']] = {k: "" for k in delay.keys()}
            else:
                time_dict[delay['timestamp']] = delay
        for k in time_dict:
            data.append({k: time_dict[k]})
        return data
